﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Jenvin.Library.Cache
{
    public class RwLockDictionaryStorage<TKey, TValue> : ICacheStorage<TKey, TValue>
    {
        private readonly Dictionary<TKey, TValue> m_storage;
        private readonly ReaderWriterLockSlim m_rwLock = new ReaderWriterLockSlim();
        public RwLockDictionaryStorage()
        {
            m_storage = new Dictionary<TKey, TValue>();
        }

        public TValue Get(TKey key)
        {
            TValue value;
            this.m_rwLock.EnterReadLock();
            try
            {
                if (this.m_storage.TryGetValue(key, out value))
                {
                    return value;
                }
            }
            finally
            {
                this.m_rwLock.ExitReadLock();
            }
            return value;
        }

        public void Set(TKey key, TValue value)
        {
            this.m_rwLock.EnterWriteLock();
            try
            {
                if (!this.m_storage.ContainsKey(key))
                {
                    this.m_storage.Add(key, value);
                }
            }
            finally
            {
                this.m_rwLock.ExitWriteLock();
            }
        }

        public bool IsContains(TKey key)
        {
            this.m_rwLock.EnterReadLock();
            try
            {
                return this.m_storage.ContainsKey(key);
            }
            finally {
                this.m_rwLock.ExitReadLock();
            }
        }

    }
}
